package com.haiheng.voiceandbook.receiver

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.voiceandbook.MyApplication
import com.haiheng.voiceandbook.commo.DownloadAPKCallBack
import java.io.File


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/11/3 0003
 * @Version: 1.0
 */
class DownloadCompleteReceiver(val callback: DownloadAPKCallBack?) : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        try {
            LogUtils.d("接收到广播：${intent?.action} ${this.hashCode()}")
            val action = intent?.action
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == action) {
                val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                // 根据 downloadId 获取下载任务的信息
                val query = DownloadManager.Query()
                query.setFilterById(downloadId)
                val downloadManager = context?.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
                val cursor = downloadManager.query(query)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    LogUtils.d("下载状态：${status}")
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        val localFileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
                        val localFile = File(Uri.parse(localFileUri).path)
                        callback?.onResult(localFile.absolutePath)
                        MyApplication.getInstance().applicationContext.unregisterReceiver(this@DownloadCompleteReceiver)
                    } else {
                        val reason =
                            cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON))
                        var reasonString = "Unknown"
                        when (reason) {
                            DownloadManager.ERROR_CANNOT_RESUME ->{
                                reasonString = "ERROR_CANNOT_RESUME"
                            }
                            DownloadManager.ERROR_DEVICE_NOT_FOUND -> reasonString =
                                "ERROR_DEVICE_NOT_FOUND"

                            DownloadManager.ERROR_FILE_ALREADY_EXISTS -> reasonString =
                                "ERROR_FILE_ALREADY_EXISTS"
                        }
                        LogUtils.d("Download 下载失败  Reason: $reasonString")
                        callback?.onError("下载失败")
                        MyApplication.getInstance().applicationContext.unregisterReceiver(this@DownloadCompleteReceiver)
                    }
                }
                cursor.close()
            }
        }catch (ex:Exception){
            LogWriter.e("下载服务异常：${ex}")
        }

    }
}

